package app.modules.menu.business.service;

import app.modules.menu.constant.MenuConstants;
import app.modules.menu.dto.web.template.WebMenuTemplateDTO;
import app.modules.menu.persistence.dao.MenuTemplateDAO;
import app.modules.menu.util.conversion.MenuTemplateConvertUtil;
import jasmine.framework.common.exception.DataNotFoundException;
import jasmine.framework.common.util.CheckUtil;
import jasmine.security.rbac.model.SecMenuTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author mh.z
 */
@Service
public class MenuTemplateService {
    private MenuTemplateDAO menuTemplateDAO;

    public MenuTemplateService(MenuTemplateDAO menuTemplateDAO) {
        this.menuTemplateDAO = menuTemplateDAO;
    }

    /**
     * 导入数据
     *
     * @param menuTemplates
     */
    @Transactional(rollbackFor = Exception.class)
    public void importMenuTemplates(List<SecMenuTemplate> menuTemplates) {
        CheckUtil.notNull(menuTemplates, "menuTemplates null");

        menuTemplateDAO.saveBatch(menuTemplates);
    }

    /**
     * 查找当前的菜单模板
     *
     * @return
     */
    public WebMenuTemplateDTO getCurrentMenuTemplate() {
        String templateCode = MenuConstants.DEFAULT_MENU_TEMPLATE_CODE;
        SecMenuTemplate secMenuTemplate = menuTemplateDAO.getByTemplateCode(templateCode);

        if (secMenuTemplate == null) {
            throw new DataNotFoundException(WebMenuTemplateDTO.class, "templateCode", templateCode);
        }

        WebMenuTemplateDTO webMenuTemplateDTO = MenuTemplateConvertUtil
                .secMenuTemplate2WebMenuTemplateDTO(secMenuTemplate);

        return webMenuTemplateDTO;
    }

    /**
     * 查询菜单模板
     *
     * @param id
     * @return
     */
    public WebMenuTemplateDTO getWebMenuTemplateDtoById(Long id) {
        SecMenuTemplate secMenuTemplate = menuTemplateDAO.getById(id);

        if (secMenuTemplate == null) {
            throw new DataNotFoundException(SecMenuTemplate.class, id);
        }

        WebMenuTemplateDTO webMenuTemplateDTO = MenuTemplateConvertUtil
                .secMenuTemplate2WebMenuTemplateDTO(secMenuTemplate);

        return webMenuTemplateDTO;
    }

}
